﻿package
{
	import flash.display.Loader;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	public class LoaderEvent extends EventDispatcher
	{
		public static const CHILD:String = "child";
		public static const SAME:String = "same";
		public static const NEW:String = "new";
		public static const COMPLETE:String = "complete";
		public static const ERROR:String = "error";
		public static const PROGRESS:String = "progress";
		
		private var loader:Loader;
		private var swfaddress:String;
		private var temp:String;
		
		public function load(url:String , type:String):void
		{
			swfaddress = url;
			temp = type;
			loader = new Loader();
			var context:LoaderContext = new LoaderContext();
			
			switch(type)
			{
				case CHILD:
				context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
				break;
				case SAME:
				context.applicationDomain = ApplicationDomain.currentDomain;
				break;
				case NEW:
				context.applicationDomain = new ApplicationDomain();
				break;
				default:
				trace("没有加载域");
			}
			LoaderListeners(loader.contentLoaderInfo);
			loader.load(new URLRequest(url),context);
		}
		
		private function LoaderListeners(dispatcher:IEventDispatcher):void
		{
			with(dispatcher)
			{
				addEventListener(Event.COMPLETE, onComplete);
				addEventListener(IOErrorEvent.IO_ERROR, onError);
				addEventListener(ProgressEvent.PROGRESS, onProgress);
				addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			}
		}
		
		public function getClass (className:String):Class
		{
			try
			{
				if(temp == SAME)
				{
					return ApplicationDomain.currentDomain.getDefinition(className) as Class;
				}
				if(temp == CHILD || temp == NEW)
				{
					return loader.contentLoaderInfo.applicationDomain.getDefinition(className) as Class;
				}
			}
			catch (e:Error)
			{
				throw new IllegalOperationError("在" + swfaddress + "没有找到" + className);
			}
			return null;
		}
		
		private function onComplete(event:Event):void
		{
			dispatchEvent(new Event(COMPLETE));
		}
		
		private function onProgress(event:Event):void
		{
			dispatchEvent(new Event(PROGRESS));
		}
		
		private function onError(event:Event):void
		{
			dispatchEvent(new Event(ERROR));
		}
	}
}